package thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;




class Account {
	private String accountNo;
	final Lock lock= new ReentrantLock();
	final Condition cond  = lock.newCondition(); 


	private boolean flag = false;

	public String getAccountNo() {
		return accountNo;
	}

	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}

	private double balance;

	public double getBalance() {
		return balance;
	}

	public void setBalance(double balance) {
		this.balance = balance;
	}

	public Account(String accountNo, double balance) {
		this.accountNo = accountNo;
		this.balance = balance;
		flag=true;
	}

	public Account() {
	}

	public int hashCode() {
		return accountNo.hashCode();
	}

	public boolean equals(Object obj) {
		if (obj != null && obj.getClass() == Account.class) {
			Account target = (Account) obj;
			return target.getAccountNo().equals(this.accountNo);
		}
		return false;
	}

	// synchronized
	public synchronized void draw(double drawAmount) throws InterruptedException {
		// lock.lock();
		// try {
		// } finally {
		// lock.unlock();
		// }
		// }
		if (!flag) {
			wait();
		} else {
			if (drawAmount < this.balance) {
				System.out.println(Thread.currentThread().getName()
						+ "getBalance:" + drawAmount);
				try {
					Thread.sleep(1);
				} catch (Exception e) {
					// TODO: handle exception
				}
				this.setBalance(this.getBalance() - drawAmount);
				System.out.println(this.accountNo + ":" + this.getBalance());
				flag = false;	
				notifyAll();
			} else
				System.out.println("no balance!");
		}
	}
}

class DrawThread extends Thread {
	private Account account;

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	private double drawAmount;

	public DrawThread(String name, Account account, double drawAmount) {
		super(name);
		this.account = account;
		this.drawAmount = drawAmount;
	}

	public void run() {
		try {
			account.draw(this.drawAmount);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class Bank {
	public static void main(String[] args) {
		Account acct = new Account("NewAccount", 1000);
		new DrawThread("Men", acct, 800).start();
		new DrawThread("Women", acct, 800).start();
	}
}